package com.immortal.core.service.impl;

import com.immortal.core.configure.storage.StorageProperties;
import com.immortal.core.module.file.FileResult;
import com.immortal.core.module.file.FileStorageType;
import com.immortal.core.module.file.UploadFileExt;
import com.immortal.core.module.file.exception.StorageException;
import com.immortal.core.module.file.exception.StorageFileNotFoundException;
import com.immortal.core.service.StorageService;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;

/**
 * <p>TODO
 *
 * @author wind
 * @version 1.0
 */
@Service
public class FileSystemStorageServiceImpl implements StorageService {
    @Override
    public String storageName() {
        return FileStorageType.SYS.name();
    }

    private final Path rootLocation;

    private StorageProperties prop;

    public FileSystemStorageServiceImpl(StorageProperties properties) {
        this.prop = properties;
        this.rootLocation = Paths.get(properties.getOos().getSys().getDiskLocation());
    }


    @Override
    public Stream<Path> loadAll() {
        try {
            return Files.walk(this.rootLocation, 1)
                    .filter(path -> !path.equals(this.rootLocation))
                    .map(this.rootLocation::relativize);
        } catch (IOException e) {
            throw new StorageException("Failed to read stored files", e);
        }

    }

    @Override
    public Path load(String filename) {
        return rootLocation.resolve(filename);
    }

    @Override
    @SneakyThrows
    public File load(String groupName, String fileName) {
        return loadAsResource(groupName == null ? fileName : groupName + fileName).getFile();
    }

    @Override
    @SneakyThrows
    public InputStream loadAsInputStream(String groupName, String fileName) {
        return loadAsResource(groupName == null ? fileName : groupName + fileName).getInputStream();
    }

    @Override
    public Resource loadAsResource(String filename) {
        try {
            Path file = load(filename);
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                throw new StorageFileNotFoundException(
                        "Could not read file: " + filename);

            }
        } catch (MalformedURLException e) {
            throw new StorageFileNotFoundException("Could not read file: " + filename, e);
        }
    }

    @Override
    public void deleteAll() {
        FileSystemUtils.deleteRecursively(rootLocation.toFile());
    }

    @Override
    public void init() {
        try {
            Files.createDirectories(rootLocation);
        } catch (IOException e) {
            throw new StorageException("Could not initialize storage", e);
        }
    }

    @Override
    public FileResult store(UploadFileExt ue) {
        try {

            try (InputStream inputStream = ue.getInputStream()) {
                if (!Files.exists(this.rootLocation.resolve(ue.getPrefix()))) {
                    Files.createDirectories(this.rootLocation.resolve(ue.getPrefix()));
                }
                Path p = this.rootLocation.resolve(ue.getPrefix() + ue.getFileName());
                if (p.toFile().exists()) {
                    IOUtils.copy(inputStream, new FileOutputStream(p.toFile()));
                } else {
                    Files.copy(inputStream, this.rootLocation.resolve(ue.getPrefix() + ue.getFileName()),
                            StandardCopyOption.REPLACE_EXISTING);
                }
            }
        } catch (IOException e) {
            throw new StorageException("Failed to store file " + ue.getFileName(), e);
        }
        String uri = prop.getOos().getSys().getBaseUrl() + prop.getOos().getSys().getDiskPrefix() + ue.getFileName();
        return FileResult.builder().code(1).uri(uri).storeType(ue.getStorageTypeList().get(0).name())
                .fileName(ue.getFileName())
                .origName(ue.getOrigFileName())
                .build();
    }
}
